package com.cssw.fyzb.tps.api.tf56pay;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cssw.fyzb.tps.config.tf56pay.TfpayConfig;
import com.itrus.cryptorole.bc.RecipientBcImpl;
import com.ydn.appserver.Action;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.appserver.annotations.Function;
import com.ydn.appserver.annotations.Parameter;
import com.ydn.appserver.annotations.Type;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import static java.util.Comparator.reverseOrder;

/**
 * @Author: yangyiqun
 * @Date: 2021/1/06 22:29
 */
@Function(description = "校验签名", parameters = {
        @Parameter(name = "data", type = Type.String, description = "数据", required = true)
})
@Component
public class VerifyTf56PaySign implements Action {

    private static final Logger logger = LoggerFactory.getLogger(VerifyTf56PaySign.class);

    @Autowired
    private TfpayConfig tf56payConfig;
    /**
     * itrusRSASign
     */
    private static final String TF_SIGN_PARAM = "tf_sign";


    @Override
    public Response execute(Request request) throws Exception {
        String data = request.getString("data");
        try {

            JSONObject params = JSON.parseObject(data);
            String sign = params.getString(TF_SIGN_PARAM);

            params.remove(TF_SIGN_PARAM);
            String oriData = sortMapByKey(params);
            RecipientBcImpl recipient = new RecipientBcImpl();
            //验签方法
            X509Certificate x509Certificate = recipient.verifySignature(oriData.getBytes(StandardCharsets.UTF_8), Base64.decodeBase64(sign));
            Map param = new HashMap();
            param.put("checkSign", true);
            return Response.success().put("data", param);
        } catch (Exception e) {
            logger.error("", e);
            return Response.fail("签名验证失败，原文已遭篡改。");
        }
    }


    private String sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        map.keySet().removeIf(key -> null == map.get(key));
        Map<String, Object> sortedMap = new TreeMap<>(reverseOrder());
        sortedMap.putAll(map);
        StringBuilder result = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedMap.entrySet()) {
            result.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        return result.toString();
    }
}
